package cn.kxm.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sun.org.apache.regexp.internal.RE;

import cn.kxm.pojo.Company;
import cn.kxm.pojo.Part;
import cn.kxm.pojo.PartType;
import cn.kxm.pojo.PayBill;
import cn.kxm.pojo.SellOrderBill;
import cn.kxm.pojo.SellOrderBillDetail;
import cn.kxm.service.CompanyService;
import cn.kxm.service.PartService;
import cn.kxm.service.SellOrderBillService;
import cn.kxm.util.ExcelUtil;
import cn.kxm.util.MakeNewCode;

@Controller
@RequestMapping("/sellorderbill")
public class SellOrderBillController extends BaseController{
	@Autowired
	@Qualifier("sellOrderBillServiceImpl")
    private SellOrderBillService sobs;
	@Autowired
	@Qualifier("partServiceImpl")
	private PartService ps;
	@Autowired	
 	private MakeNewCode makeNewCode;
	@Autowired
	private CompanyService cs;
	
	@RequestMapping("/findall")
	@ResponseBody
	public Object findAll(@RequestParam(value="findcode",required=false)String findcode,
			@RequestParam(value="findstartDate",required=false)String findstartDate,
			@RequestParam(value="findendDate",required=false)String findendDate,
			@RequestParam(value="findsupplierName",required=false)String findsupplierName,
			Integer page,Integer rows){
		List<Map<String, Object>> list=sobs.getSellOrderBills(findcode, findstartDate, findendDate, findsupplierName, (page-1)*rows, rows);
		int total=sobs.getSellOrderBillCount(findcode, findstartDate, findendDate, findsupplierName);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("total",total);
		map.put("rows",list);
		return JSONArray.toJSONString(map);
	}
	
	@RequestMapping("/findallcompany")
	@ResponseBody
	public Object findAllCompany(@RequestParam(value="findName",required=false)String findName,
			@RequestParam(value="findCode",required=false)String findCode,
			@RequestParam(value="findType",required=false)Integer findType,
			Integer page,Integer rows){
		List<Company> list=cs.findAll(findCode, findName, findType, (page-1)*rows, rows);
		int total=cs.getCount(findCode, findName, findType);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("total",total);
		map.put("rows",list);
		return JSONArray.toJSONString(map);
	}
	
	@RequestMapping("/findallpart")
	@ResponseBody
	public Object findAllPart(@RequestParam(value="partBrand",required=false)String partBrand,
			@RequestParam(value="partNo",required=false)String partNo,
			@RequestParam(value="partName",required=false)String partName,
			@RequestParam(value="partTypeId",required=false)Integer partTypeId,
			Integer page,Integer rows){
		List<Part> list=ps.getPartList(partBrand, partNo, partName, partTypeId, (page-1)*rows, rows);
		int total=ps.getPartCount(partBrand, partNo, partName, partTypeId);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("total",total);
		map.put("rows",list);
		return JSONArray.toJSONString(map);
	}
	
	@RequestMapping("/findallpartname")
    @ResponseBody
    public Object findAllTypeName(){
    	List<PartType> list=ps.getPartTypeList();
    	PartType p=new PartType();
    	p.setId(0);
    	p.setTypeName("--请选择--");
    	list.add(0,p);
    	return JSON.toJSONString(list);
    }
	
	@RequestMapping("/showsellorderoillbycode")
	public String showSellOrderBillByCode(Model model,String code){
		Map<String, Object> sellOrderBill=sobs.getSellOrderBillByCode(code);
        model.addAttribute("sellOrderBill",sellOrderBill);
		return "web/goods/displaySalesOrder"; 		
	}
	
	@RequestMapping("/updatesellorderoillbycode")
	public String updateSellOrderBillByCode(Model model,String code){
		Map<String, Object> sellOrderBill=sobs.getSellOrderBillByCode(code);
		model.addAttribute("sellOrderBill",sellOrderBill);
		if((Integer)sellOrderBill.get("checkStatus")==1){
			return "web/goods/updateSalesOrder"; 
		}else{
			return "web/goods/displaySalesOrder"; 
		}
	}
	
	@RequestMapping("/findpartsbysellcode")
    @ResponseBody
    public Object findPartsBySellCode(String sellcode){
		List<Map<String, Object>> list=sobs.getfindPartsBySellCode(sellcode);
    	return JSON.toJSONString(list);
    }
	
	@RequestMapping("/addSellOrderBill")
	@ResponseBody
	public Object addSellOrderBill(SellOrderBill sellOrderBill,String data){
		Map<String, Object> map=new HashMap<String, Object>();
		sellOrderBill.setPayStatus(1);
		sellOrderBill.setCheckStatus(1);
		sellOrderBill.setOutstorageStatus(1);
		
		List<Map<String,Object>> oldList=(List<Map<String, Object>>) JSON.parse(data);
		List<SellOrderBillDetail> list=new ArrayList<SellOrderBillDetail>();
		if(oldList!=null){
			for (int i = 0; i < oldList.size()-1; i++) {
				Map<String,Object> a=oldList.get(i);
			    SellOrderBillDetail sellOrderBillDetail=new SellOrderBillDetail();
			    sellOrderBillDetail.setPartCode(a.get("code").toString());
			    sellOrderBillDetail.setAmount(Integer.parseInt(a.get("amount").toString()));
			    sellOrderBillDetail.setPrice(Double.parseDouble(a.get("price").toString()));
			    if(a.get("memo")!=null){
			    	sellOrderBillDetail.setMemo(a.get("memo").toString());
			    }
			    sellOrderBillDetail.setBillCode(sellOrderBill.getCode());
			    list.add(sellOrderBillDetail);
			}
			if(sobs.addSellOrder(sellOrderBill, list)==(list.size()+1)){
				map.put("result", "success");
			}else{
			    map.put("result", "error");
			}
			
		}else {
			map.put("result", "error");
		}
		
		return JSON.toJSONString(map);
	}
	
	@RequestMapping("/updatesellorderbill")
    @ResponseBody
    public Object updateSellOrderBill(SellOrderBill sellOrderBill,String data){
		Map<String, Object> map=new HashMap<String, Object>();
		
		List<Map<String,Object>> oldList=(List<Map<String, Object>>) JSON.parse(data);
		List<SellOrderBillDetail> list=new ArrayList<SellOrderBillDetail>();
		if(oldList!=null){
			for (int i = 0; i < oldList.size()-1; i++) {
				Map<String,Object> a=oldList.get(i);
			    SellOrderBillDetail sellOrderBillDetail=new SellOrderBillDetail();
			    sellOrderBillDetail.setPartCode(a.get("code").toString());
			    sellOrderBillDetail.setAmount(Integer.parseInt(a.get("amount").toString()));
			    sellOrderBillDetail.setPrice(Double.parseDouble(a.get("price").toString()));
			    if(a.get("memo")!=null){
			    	sellOrderBillDetail.setMemo(a.get("memo").toString());
			    }
			    sellOrderBillDetail.setBillCode(sellOrderBill.getCode());
			    list.add(sellOrderBillDetail);
			}
			if(sobs.updateSellOrder(sellOrderBill, list)==(list.size()+2)){
				map.put("result", "success");
			}else{
				System.out.println(11);
			    map.put("result", "error");
			}
		}else{
			map.put("result", "error");
		}
		return JSON.toJSONString(map);
	}
	
	@RequestMapping("/makenewcode")
    @ResponseBody
    public Object makeNewCode(String prefix){
		Map<String,Object> map=new HashMap<String, Object>();
    	String code=makeNewCode.getRandomCodeByPrefix(prefix);
    	map.put("result",code);
    	return JSON.toJSONString(map);
    }
	
	@RequestMapping("/delsellorderbill")
    @ResponseBody
    public Object delSellOrderBill(String code){
		Map<String,Object> map=new HashMap<String, Object>();
		if(sobs.delOne(code)==1){
			map.put("result","success");
		}else{
			map.put("result","error");
		}
    	return JSON.toJSONString(map);
    }
	
	@RequestMapping("/delallsellorderbill")
    @ResponseBody
    public Object delAllSellOrderBill(String codes){
		Map<String,Object> map=new HashMap<String, Object>();
		List<String> code=(List<String>) JSON.parse(codes);
		for(int i=0;i<code.size();i++){
			if(sobs.delOne(code.get(i).toString())==1){
				map.put("result","success");
			}else{
				map.put("result","error");
			}
		}
    	return JSON.toJSONString(map);
    }
	
	@RequestMapping("/findallofferpricebill")
	@ResponseBody
	public Object findAllOfferPriceBill(@RequestParam(value="findcode",required=false)String findcode,
			@RequestParam(value="findstartDate",required=false)String findstartDate,
			@RequestParam(value="findendDate",required=false)String findendDate,
			String customName,
			Integer page,Integer rows){
		System.out.println(customName);
		List<Map<String, Object>> list=sobs.getOfferPriceBills(findcode, findstartDate, findendDate, customName,(page-1)*rows, rows);
		System.out.println(list);
		int total=sobs.getOfferPriceBillsCount(findcode, findstartDate, findendDate,customName);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("total",total);
		map.put("rows",list);
		return JSONArray.toJSONString(map);
	}
	
	@RequestMapping("/findpartbycode")
	@ResponseBody
	public Object findPartByCode(String data){
	   List<Map<String,Object>> oldList=(List<Map<String, Object>>) JSON.parse(data);
	   List<Map<String,Object>> newList=new ArrayList<Map<String,Object>>();
	   if(oldList!=null){
		   for(int i = 0; i < oldList.size(); i++){
			   newList.addAll(ps.getPartListByBillCode(oldList.get(i).get("code").toString()));
		   }
	   } 
	   return JSONArray.toJSONString(newList);
    }
	
	@RequestMapping("/updateAuditing")
	public String updateAuditing(String sellcode,ServletRequest request){
		sobs.updateAuditing(sellcode);
		Map<String, Object> sellOrderBill=sobs.getSellOrderBillByCode(sellcode);
        if((Integer)sellOrderBill.get("checkStatus")==1){
        	return "redirect:/sellorderbill/updatesellorderoillbycode?code="+sellcode;
        }else{
        	return "redirect:/sellorderbill/showsellorderoillbycode?code="+sellcode;
        }
	}
	
	@RequestMapping("/addAuditing")
	@ResponseBody
	public Object addAuditing(SellOrderBill sellOrderBill,String data){
		Map<String, Object> map=new HashMap<String, Object>();
		sellOrderBill.setPayStatus(1);
		sellOrderBill.setCheckStatus(2);
		sellOrderBill.setOutstorageStatus(1);
		
		List<Map<String,Object>> oldList=(List<Map<String, Object>>) JSON.parse(data);
		List<SellOrderBillDetail> list=new ArrayList<SellOrderBillDetail>();
		if(oldList!=null){
			for (int i = 0; i < oldList.size()-1; i++) {
				Map<String,Object> a=oldList.get(i);
			    SellOrderBillDetail sellOrderBillDetail=new SellOrderBillDetail();
			    sellOrderBillDetail.setPartCode(a.get("code").toString());
			    sellOrderBillDetail.setAmount(Integer.parseInt(a.get("amount").toString()));
			    sellOrderBillDetail.setPrice(Double.parseDouble(a.get("price").toString()));
			    if(a.get("memo")!=null){
			    	sellOrderBillDetail.setMemo(a.get("memo").toString());
			    }
			    sellOrderBillDetail.setBillCode(sellOrderBill.getCode());
			    list.add(sellOrderBillDetail);
			}
			if(sobs.addSellOrder(sellOrderBill, list)==(list.size()+1)){
				map.put("result", "success");
			}else{
			    map.put("result", "error");
			}
			
		}else {
			map.put("result", "error");
		}
		
		return JSON.toJSONString(map);
	}
	
	@RequestMapping("/Revoke")
	public String Revoke(String sellcode){
		Map<String, Object> sellOrderBill=sobs.getSellOrderBillByCode(sellcode);
		if((Integer)sellOrderBill.get("outstorageStatus")==1){
			sobs.updateUnaudited(sellcode);
			return "redirect:/sellorderbill/updatesellorderoillbycode?code="+sellcode;
		}else{
			return "redirect:/sellorderbill/showsellorderoillbycode?code="+sellcode;
		}
	}
	
	/** 
	 * @Title: setResponseHeader 
	 * @Description: 发送响应流方法
	 * @param response
	 * @param fileName  参数说明 
	 * @return void    返回类型 
	 * @throws 
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(),"ISO8859-1");
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	@RequestMapping("getExcel")
	public void export(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="findcode",required=false)String findcode,
			@RequestParam(value="findstartDate",required=false)String findstartDate,
			@RequestParam(value="findendDate",required=false)String findendDate,
			@RequestParam(value="findsupplierName",required=false)String findsupplierName) throws Exception {
		//获取数据
		List<Map<String, Object>> list=sobs.getSellOrderBillList(findcode, findstartDate, findendDate, findsupplierName);
		//excel标题
		String[] title= {"订单编号","订单日期","客户名称","总货值","联系人","联系方式","审核状态","支付状态"};
		System.out.println(title);

		//excel文件名
		String fileName="销售订单管理"+new Date()+".xls";
		System.out.println(fileName);

		//sheet名
		String sheetName="销售订单管理";
		System.out.println(sheetName);
		
		//装载数据
		String[][] content=new String[list.size()][title.length];
		for(int i=0;i<list.size();i++) {
			Map<String,Object> s=list.get(i);
			content[i][0]=(String) s.get("code");
			content[i][1]=(s.get("orderTime")).toString();
			content[i][2]=(String) s.get("customName");
			content[i][3]=String.valueOf(s.get("money"));
			content[i][4]=(String) s.get("linkman");
			content[i][5]=(String) s.get("phone");
			if((Integer) s.get("checkStatus")==1) {
				content[i][6]="未审核";
			}else {
				content[i][6]="已审核";
			}
			if((Integer) s.get("payStatus")==1) {
				content[i][7]="未支付";
			}else if((Integer) s.get("payStatus")==2){
				content[i][7]="已支付";
			}
		}
		System.out.println(String.valueOf(content));
		
		//创建HSSF
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
		System.out.println(wb);

		//响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os=response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	} 
	
	
}
